package com.example.servicehandler;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

	
	private EditText inputText;
	private Button submit;
	private ProgressDialog progressDialog;
	
	private ServiceHandler requestHander = new ServiceHandler();

	private Handler handler = new Handler() {
		
		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		
		inputText = (EditText) findViewById(R.id.editText);
		submit = (Button) findViewById(R.id.buttonSubmit);
		
		//slack
		inputText.setText("http://api.androidhive.info/contacts/");
		
		submit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				progressDialog = ProgressDialog.show(MainActivity.this, "Aguarde", "Realizando request...", true, false);
				
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						String url = inputText.getText().toString();
						String output = requestHander.makeServiceCall(url, ServiceHandler.GET);
						Log.v("REQUEST", output);
						handler.sendEmptyMessage(200);
					}
				}).start();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
